﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;

namespace TFit
{
    public partial class TFitClientMainForm : Form
    {
        private User currentUser;
        private bool isSettingsNeedsToBeSaved = false;


        /// <summary>
        /// Initializes a new instance of the <see cref="TFitClientMainForm"/> class.
        /// </summary>
        public TFitClientMainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Выводит выбранную информацию в DataGrid
        /// </summary>
        /// <param name="exercises">Список подходов.</param>
        private void FillDataGrid(IEnumerable exercises)
        {
            exerciseBindingSource.Clear();
            foreach (var ev in exercises)
            {
                exerciseBindingSource.Add(ev);
            }
            toolStripStatusLabel2.Text = "Записей в таблице: " + exerciseBindingSource.Count.ToString();
            FillCalendar();
        }
        /// <summary>
        /// Выделить в каллендаре числа, о которых есть записи в истории текущего пользователя
        /// </summary>
        private void FillCalendar()
        {
            IEnumerable<DateTime> q = from ex in currentUser.GetHistory()
                    select ex.Date;
            monthCalendar1.BoldedDates = q.ToArray<DateTime>();
        }
        /// <summary>
        /// Загрузить настройки программы
        /// </summary>
        private void LoadSettings()
        {
            if ( File.Exists( GetSettingsFileName() ) )
            {
                var settings = XDocument.Load(GetSettingsFileName());
                var winPos = settings.Root.Element("window-settings").Element("location");
                var usrXElem = settings.Root.Element("users");

                this.Location = new System.Drawing.Point(Int32.Parse(winPos.Element("x-position").Value),
                                                         Int32.Parse(winPos.Element("y-position").Value));

                foreach (var user in usrXElem.Elements())
                {
                    //генерация меню
                    ToolStripMenuItem itm = new ToolStripMenuItem(user.Element("user-name").Value);
                    itm.Click += new EventHandler(itm_Click);

                    if (user.Attribute("current").Value == "true")  //ищем активного пользователя
                    {
                        SetCurrentUser(new User(user.Element("user-name").Value, "passw"));
                        itm.Checked = true;
                    }
                    this.changeUserToolStripMenuItem.DropDownItems.Add(itm);

                }
                if (currentUser == null)
                    SetCurrentUser(new User("No User","no_passw"));

                if (File.Exists("history\\" + currentUser.Name + ".dat"))
                    loadHistoryToolStripMenuItem_Click(null, null);
            }
            else
            {
                SetCurrentUser(new User("Unknown User","no_passw"));
                loadHistoryToolStripMenuItem.Enabled = false;
            }
              
        }
        /// <summary>
        /// Сохранить настройки программы
        /// </summary>
        private void SaveSettings()
        {
            if (!File.Exists(GetSettingsFileName()))
            {
                XDocument settings = new XDocument
                (
                    new XElement("settings",
                        new XElement("users",
                            new XElement("user",
                                new XAttribute("current", true),
                                new XElement("user-name", currentUser.Name),
                                new XElement("history", currentUser.Name + ".dat")
                                )
                            ),
                        new XElement("window-settings",
                            new XElement("location",
                                new XElement("x-position", this.Location.X),
                                new XElement("y-position", this.Location.Y)
                                )
                            )
                    )
                );
                settings.Declaration = new XDeclaration("1.0", "utf-8", "true");
                settings.Save(GetSettingsFileName());
            }
            else
            {
                XDocument settings = XDocument.Load(GetSettingsFileName());
                foreach (var item in settings.Root.Element("users").Elements())
                {
                    if (item.Element("user-name").Value == currentUser.Name)
                    {
                        item.Attribute("current").Value = "true";
                    }
                    else
                    {
                        item.Attribute("current").Value = "false";
                    }
                }
                settings.Root.Element("window-settings").Element("location").Element("x-position").Value = this.Location.X.ToString();
                settings.Root.Element("window-settings").Element("location").Element("y-position").Value = this.Location.Y.ToString();

                settings.Save(GetSettingsFileName());
            }
        }
        /// <summary>
        /// Получить имя файла настроек
        /// </summary>
        /// <returns>Относительный путь к файлу настроек</returns>
        private string GetSettingsFileName()
        {
            return "settings.xml";
        }
        /// <summary>
        /// Установить данного пользователя, как текущего
        /// </summary>
        /// <param name="u">Пользователь</param>
        private void SetCurrentUser(User u)
        {
            currentUser = u;
            this.Text = currentUser.Name;
            FillDataGrid(currentUser.GetHistory());
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!Directory.Exists("history\\"))
            {
                Directory.CreateDirectory("history\\");
            }
            LoadSettings();
        }

        /// <summary>
        /// Raises the <see cref="E:Closing"/> event.
        /// </summary>
        /// <param name="ce">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        protected override void OnClosing(System.ComponentModel.CancelEventArgs ce)
        {
            base.OnClosing(ce);
            if (isSettingsNeedsToBeSaved)
            {
                DialogResult dlr = MessageBox.Show("Сохранить изменения в истории?", "Вопрос", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dlr == DialogResult.Yes)
                {
                    SaveSettings();
                }
                if (dlr == DialogResult.Cancel)
                {
                    ce.Cancel = true;
                }
            }
        }

        private void Form1_Move(object sender, EventArgs e)
        {
            isSettingsNeedsToBeSaved = true;
        }

        private void itm_Click(object sender, EventArgs e)
        {
            foreach (ToolStripMenuItem item in this.changeUserToolStripMenuItem.DropDownItems)
            {
                if (item.Text == sender.ToString())
                {
                    item.Checked = true;
                    SetCurrentUser(new User(item.Text, "pasw"));
                    currentUser.LoadHistory();
                }
                else
                {
                    item.Checked = false;
                }
            }
            isSettingsNeedsToBeSaved = true;
            FillDataGrid(currentUser.GetHistory());
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewUserDialog dlg = new NewUserDialog();
            if (DialogResult.OK == dlg.ShowDialog())
            {
                SetCurrentUser(dlg.GetUser());

                //add user to changeUser Menu
                ToolStripMenuItem itm = new ToolStripMenuItem(currentUser.Name);
                itm.Click += new EventHandler(itm_Click);
                itm.Checked = true;
                foreach (ToolStripMenuItem item in changeUserToolStripMenuItem.DropDownItems)
                {
                    item.Checked = false;
                }
                this.changeUserToolStripMenuItem.DropDownItems.Add(itm);

                var userInf = new XElement("user",
                        new XAttribute("current", true),
                        new XElement("user-name", currentUser.Name),
                        new XElement("history", currentUser.Name + ".dat")
                        );

                if (File.Exists(GetSettingsFileName()))
                {
                    var settings = XDocument.Load(GetSettingsFileName());
                    foreach (var elem in settings.Root.Element("users").Elements())
                    {
                        elem.FirstAttribute.SetValue(false);
                    }
                    settings.Root.Element("users").Add(userInf);
                    settings.Save(GetSettingsFileName());
                }
                else
                {
                    SaveSettings();
                }
            }
        }

        private void saveHistoryToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            currentUser.SaveHistory();
            loadHistoryToolStripMenuItem.Enabled = true;
        }

        private void loadHistoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentUser.LoadHistory();
            FillDataGrid(currentUser.GetHistory());
        }

        private void saveSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveSettings();
            isSettingsNeedsToBeSaved = false;
        }

        private void exportToCsvToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.AddExtension = true;
            saveFileDialog1.Filter = "(*.csv)|*.csv";
            DialogResult dlr = saveFileDialog1.ShowDialog();
            if (dlr == DialogResult.OK)
            {
                var filePath = saveFileDialog1.FileName;

                List<string> lines = new List<string>();
                lines.Add(";" + currentUser.Name + ";");
                lines.Add("Дата;Левая рука;Правая рука");
                foreach (Exercise el in exerciseBindingSource)
                {
                    lines.Add(el.Date.ToShortDateString() + "; " + el.LeftCounter.ToString() + " ;" + el.RhightCounter.ToString());
                }

                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 8);
                StreamWriter sr = new StreamWriter(fs, System.Text.Encoding.GetEncoding(1251));

                foreach (var line in lines)
                {
                    sr.WriteLine(line);
                }
                sr.Close();
            }



        }

        private void addExToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddExercieseDialog dlg = new AddExercieseDialog();
            dlg.StartPosition = FormStartPosition.CenterParent;
            DialogResult dlgRes = dlg.ShowDialog();
            if (dlgRes == DialogResult.OK)
            {
                currentUser.AddExerciseToHistory(dlg.GetExercise());
                //FIXME: сделать проверку на необходимость сохранения перед выходом
                FillDataGrid(currentUser.GetHistory());
                isSettingsNeedsToBeSaved = true;
            }
        }
       
        private void bestExButton_Click(object sender, EventArgs e)
        {
            var q = from ev in currentUser.GetHistory()
                    where (ev.RhightCounter == currentUser.GetHistory().Max(t => t.RhightCounter)) ||
                    (ev.LeftCounter == currentUser.GetHistory().Max(t => t.LeftCounter))
                    select ev;

            FillDataGrid(q);
        }
        
        private void worstExButton_Click(object sender, EventArgs e)
        {
            var q = from ex in currentUser.GetHistory()
                    where (ex.LeftCounter == currentUser.GetHistory().Min(t => t.LeftCounter) ||
                            ex.RhightCounter == currentUser.GetHistory().Min(t => t.RhightCounter))
                    select ex;

            FillDataGrid(q);
        }

        private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
        {
            var q = from ex in currentUser.GetHistory()
                    where ((ex.Date >= e.Start) && (ex.Date <= e.End))
                    select ex;
            FillDataGrid(q);
        }

        private void deleteCurrentUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("Удалить текущего пользователя и его историю?", "Подтвердите удаление",
                                                         MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.Yes)
            {
                if (File.Exists(GetSettingsFileName()))
                {
                    var settings = XDocument.Load(GetSettingsFileName());
                    string deletedUserName = currentUser.Name;

                    //Сохраняем настройки, и выкидываем текущего пользователя из списка.
                    var windowSett = settings.Root.Element("window-settings"); 
                    var newUserList = from ex in settings.Root.Element("users").Elements()
                                      where ex.Element("user-name").Value != deletedUserName
                            select ex;

                    settings.Root.Element("users").Remove();
                    //удаляем файл истории пользователя
                    if (File.Exists("history\\" + deletedUserName + ".dat"))
                    {
                        File.Delete("history\\" + deletedUserName + ".dat");
                    }

                    //Выбираем первого пользователя, и устанавливаем его текущим
                    foreach (var item in newUserList)
                    {
                        if (item.Element("user-name").Value != deletedUserName)
                        {
                            item.Attribute("current").Value = "true";
                            SetCurrentUser(new User(item.Element("user-name").Value, "no_passw"));
                            break;
                        }
                    }
                    XElement users = new XElement("users", newUserList);
                    settings.Root.Add(users);

                    //Записываем файл с настройками
                    File.Delete(GetSettingsFileName());
                    settings.Save(GetSettingsFileName());
                    
                    //Обновляем список выбора пользователя
                    ToolStripMenuItem itemTodel = new ToolStripMenuItem();
                    foreach (ToolStripMenuItem item in this.changeUserToolStripMenuItem.DropDownItems)
                    {
                        if (item.Text == currentUser.Name)
                        {
                            item.Checked = true;
                        }
                        else
                        {
                            if (item.Text == deletedUserName)
                            {
                                itemTodel = item;
                            }
                            else
                                item.Checked = false;
                        }
                    }
                    this.changeUserToolStripMenuItem.DropDownItems.Remove(itemTodel);

                    if (File.Exists("history\\" + currentUser.Name + ".dat"))
                        loadHistoryToolStripMenuItem_Click(null, null);
                }
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutDialog ab = new AboutDialog();
            ab.ShowDialog();
        }

        private void ViewStatbutton_Click(object sender, EventArgs e)
        {
            TFit.Dialogs.StatisticsDialog statDialog = new TFit.Dialogs.StatisticsDialog();
            statDialog.Show();
        }
    }
}
